var study = {};
study.social = false;
study.facebook = false;
study.editors = {};
study.floating_tag_table_visible = false;

study.ready = function() {
	// select an element by ID, and register an onclick handler
	//$("#addset").click(study.renderAddSetForm);
	var page = window.location.pathname;
	if (page == "/") {
		study.displayEditEntriesAndStudyPage();
	} else if (page == "/faq.html") {
		$(".stripeMe tr:nth-child(even)").addClass("alt");
	} else if (page == "/decks/search.html") {
		$(".stripeMe tr:nth-child(even)").addClass("alt");
		$(".resubscribe_link").click(study.search_result_resubscribe);
		$('.resubscribe_link').parent().parent().mouseover(study.search_result_update_tooltip_handler);
		$('.LibraryStatus').click(study.do_nothing_handler); // For now, these icons do nothing if user click on them
		$('.NeedMyTooltip').each(study.make_tooltip_element);
	} else if (page == "/deck/create-form.html") {
		$("#submit").click(study.submitAddSetForm);
	} else if (page == "/library.html") {
		$(".stripeMe tr:nth-child(even)").addClass("alt");
		$("a.setlink").click(study.library_deck_link_click_handler);
		$('.LibraryStatus').click(study.library_toggle_following_status_handler);
		//$('body').delegate('a.LibraryStatus','click',study.library_toggle_following_status_handler);
		$('.LibraryStatus').mouseover(study.library_create_tooltip_element_handler);
		$('a.setlink').mouseover(study.library_create_tooltip_deck_link);
		$('#library_delete_authored_decks').click(study.library_delete_authored_decks_click_handler);
		$('#library_delete_not_authored_decks').click(study.library_delete_not_authored_decks_click_handler);
		$('.authored_checkbox').click(study.warnDeleteNonEmptyDecks_handler);
	} else if (page == '/preferences') {
		$("#submit").click(study.savePreferences_handler);
		$('#location_select').change(study.locationOnchange);
	}

	if (page != "/") {
		$('#menu_share, #menu_study_materials, #menu_edit_deck, #menu_contributors, #menu_feedback, #importLink, #exportLink, #printLink, #deleteEntriesLink, #unsubscribe_link, #menuDeleteDeckLink, #showFloatingTagsDivLink').parent().hide();
	}

	$('#searchbtn').click(study.search);
	top_horizontal_menu = new menu.dd('top_horizontal_menu'); // This has to be a global variable
	top_horizontal_menu.init('menu');
	// We are using http://dynamicdrive.com/dynamicindex5/speechbubblestooltip.htm for tooltip
	$('.NeedTooltip').speechbubble({url:'/tooltips_speechbubble.txt'});
	$('#help_link').click(study.help_link_click_handler);
	$.fn.tooltip.map = {
		'importLink': {
			'position': 'left',
			'verticalAlignment': 'middle',
			'useSpeechBubble': true
		},
		'exportLink': {
			'position': 'left',
			'verticalAlignment': 'middle',
			'useSpeechBubble': true
		},
		'printLink': {
			'position': 'left',
			'verticalAlignment': 'middle',
			'useSpeechBubble': true
		},
		'unsubscribe_link': {
			'position': 'left',
			'verticalAlignment': 'middle',
			'useSpeechBubble': true
		},
		'library_delete_not_authored_decks': {
			'position': 'right',
			'verticalAlignment': 'middle',
			'useSpeechBubble': true
		},
		'library_delete_authored_decks': {
			'position': 'right',
			'verticalAlignment': 'middle',
			'useSpeechBubble': true
		},
		'menuDeleteDeckLink': {
			'position': 'left',
			'verticalAlignment': 'middle',
			'useSpeechBubble': true
		}
	};
	$('.NeedMyTooltip').mouseover($.fn.tooltip.show).mouseout($.fn.tooltip.hide);
	$('body').delegate('td', 'click', study.thelist_click_handler);
	$('body').delegate('td', 'dblclick', study.editEntry);
	$('body').delegate('.deletebtn', 'click', study.deleteEntry);
	$('body').delegate('#edit_entry', 'click', study.editEntry);
	$('body').delegate('#add_entry', 'click', study.showAddOrEditEntryDiv_handler);
	$('body').delegate('#add_save_entry', 'click', study.addOrSaveEntry);
	$('body').delegate('#ourFeedback_send', 'click', function(e) { $('#our_feedback_contact_form').submit(); });
	$('body').delegate('.facebookShareLink', 'click', study.shareOnFacebook_click);
	$('#menu_share').click(function(e) { e.preventDefault(); study.display_share_modal(); return false; });
	$('#menu_study_materials').click(function(e) { e.preventDefault(); study.display_study_materials_modal(); return false; });
	$('#menu_edit_deck').click(function(e) { e.preventDefault(); study.display_edit_deck(); return false; });
	$('#editDeck_save').click(study.submitEditSetForm);
	$('#editDeck_cancel').click(function(e){ e.preventDefault(); window.location.href = study.baseURL; return false;});
	$('#menu_contributors').click(function(e) { e.preventDefault(); study.display_contributors_modal(); return false; });
	$('body').delegate('#contributor_search_btn', 'click', study.search_for_potential_contributors);
	$('body').delegate('#remove_contributors_btn', 'click', study.removeContributors);
	$('body').delegate('#contributor_add_btn', 'click', study.addContributors);
	$('#menu_feedback').click(function(e) { e.preventDefault(); study.display_deck_feedback_page(); return false; });
	$('#feedback_sendBtn').click(study.sendFeedback);
	$('#showFloatingTagsDivLink').click(function(e){ e.preventDefault(); study.showFloatingTagTable(); return false; });
	$('#importLink').click(study.importLinkClicked);
	$('#exportLink').click(study.exportLinkClicked);
	$('#printLink').click(study.printLinkClicked);
	$('#deleteEntriesLink').click(study.deleteEntries_clickHandler);
	$('#menuDeleteDeckLink').click(study.menuDeleteDeckLink_clickHandler);
	$('#unsubscribe_link').click(function(e) { e.preventDefault(); study.display_unsubscribe_modal(); return false; });
	$('body').delegate('#unsubscribe_confirmed', 'click', function(e) { e.preventDefault(); study.display_unsubscribe_confirmed_modal(); return false; });
	$('.deleteTagBtn').astound_droppable(study.deleteTag);
	$('body').delegate('#add_location_btn', 'click', study.displayAddLocationDialog);
	$('body').delegate('#confirm_location_btn', 'click', study.confirmAddLocation);
	$('body').delegate('#delete_location_btn', 'click', study.deleteLocation);
	$('body').delegate('#save_location_settings_btn', 'click', study.saveLocationDecks);
	$('body').delegate('.change_objective', 'click', study.displaySetObjectiveDialog);
	$('body').delegate('.set_objective', 'click', study.displaySetObjectiveDialog);
	$('body').delegate('#object_calendar_day_btn', 'click', study.setObjectiveCalendarDays);
	$('body').delegate('#download', 'click', study.displayDownloadDialog);
};

study.hideDeckSpecificMenuEntries = function() {
	$('#menu_share, #menu_study_materials, #menu_edit_deck, #menu_contributors, #menu_feedback, #importLink, #exportLink, #printLink, #deleteEntriesLink, #unsubscribe_link, #menuDeleteDeckLink, #showFloatingTagsDivLink').parent().hide();
};

study.showDeckSpecificMenuEntries = function() {
	$('#menu_share, #menu_study_materials, #menu_edit_deck, #menu_contributors, #menu_feedback, #importLink, #exportLink, #printLink, #deleteEntriesLink, #unsubscribe_link, #menuDeleteDeckLink, #showFloatingTagsDivLink').parent().show();
};

study.displayDownloadDialog = function(e) {
	e.preventDefault();
	var gm = $('#genericModal');
	var html = '<p>To download our extension for Firefox, please go to <a href="https://addons.mozilla.org/addon/astoundlearning" style="text-decoration: underline">https://addons.mozilla.org/addon/astoundlearning</a></p><p>Currently we do not have extension for other browsers, but we plan to implement them in the future.</p>';
	gm.hide().html(html);
	gm.dialog({'autoOpen': false, 'title': '', 'width': 460}).dialog('open');
	return false;
};

study.displaySetObjectiveDialog = function(e) {
	e.preventDefault();
	var deck_key = $(this).parent().parent().parent().find('input.location_decks').val();
	$('#deckKey_setObjective').text(deck_key);
	var gm = $('#genericModal');
	var html = '<form method="POST" action="/"><p>Please indicate the number of calendar days that you want to complete this deck: <input type="text" maxlength="3" id="objective_calendar_day"/> <span class="button" id="object_calendar_day_btn">Ok</span></form><div id="objective_error" class="error"></div>';
	gm.hide().html(html);
	gm.dialog({'autoOpen': false, 'title': '', 'width': 460}).dialog('open');
	return false;
};

study.setObjectiveCalendarDays = function(e) {
	var calendarDays = $.trim($('#objective_calendar_day').val());
	if (calendarDays > 0) {
		var url = study.baseURL + '/set/save_objective.json';
		var d = {};
		d.setKey = $('#deckKey_setObjective').text();
		d.objective_calendar_days = calendarDays;
		$.astound_ajax({'url': url, 'type': 'POST', 'data': d, 'success': function(json,txtStatus) {
			var gm = $('#genericModal');
			gm.html('Objective saved successfully');

			// Find the row which contains the deck that the user set the objective for
			// so that we can update it appropriately
			var input_fields = $('#location_decks').find('input.location_decks');
			var tr;
			for (var i = 0, j = input_fields.length; i < j; i++) {
				var v = $(input_fields[i]).val();
				if (v == d.setKey) {
					tr = $(input_fields[i]).parent().parent();
				}
			}
			var entryCount = tr.find('span.locationDeck_entryCount').text();
			var xstr = 'entry';
			if (entryCount != 1) {
				xstr = 'entries';
			}
			var objective_html = 'Contains ' + entryCount + ' ' + xstr + '. ';
			var target_finish_date = new Date();
			target_finish_date.setDate(target_finish_date.getDate() + parseInt(calendarDays));
			target_finish_date = target_finish_date.toLocaleDateString();
			objective_html += 'Objective set for ' + calendarDays + ' days.  Should be finished on ' + target_finish_date + '. ' + '<a href="javascript:void(0)" class="change_objective">Change objective</a>';
			objective_html = '(' + objective_html + ')';
			tr.find('span.location_deck_objective').html(objective_html);
		}});
	} else {
		$('#objective_error').html('The provided values is not a valid number');
	}
};

study.saveLocationDecks = function(e) {
	var d = {};
	d.locationKey = study.getSelectedValue('#location_select');
	var checkboxes = $('input.location_decks:checked');
	var selectedDecks = new Array();
	checkboxes.each(function() {
			var key = $(this).val();
			selectedDecks.push(key);
	});

	d.selectedDecks = selectedDecks;
	var url = study.baseURL + '/preferences/save_location_decks.json';
	console.log(url);
	$.astound_ajax({'url': url, 'type': 'POST', 'data': d, 'success': function(json,txtStatus) {
			study.notify('Notification','Successfully saved settings for selected location.', {height: 60});
	}});
};

study.deleteLocation = function(e) {
	var d = {};
	d.locationKey = study.getSelectedValue('#location_select');
	var url = study.baseURL + '/preferences/delete_location.json';
	$.astound_ajax({'url': url, 'type': 'POST', 'data': d, 'success': function(json,txtStatus) {
			study.displayLocationDropdown(json.locations);
			$('#location_select').change();
	}});
};

study.confirmAddLocation = function(e) {
	var gm = $('#genericModal');
	gm.dialog('close');
	var d = {};
	d.locationName = $('#new_location').val();
	var url = study.baseURL + '/preferences/add_location.json';
	$.astound_ajax({'url': url, 'type': 'POST', 'data': d, 'success': function(json,txtStatus) {
			study.displayLocationDropdown(json.locations);
			$('#location_select').change();
	}});
};

study.displayLocationDropdown = function(locations) {
	var html = '<option value="">Select a location you want to edit</option>';
	for (var i = 0, j = locations.length; i < j; i++) {
		var loc = locations[i];
		html += '<option value="' + loc[0] + '" ' + loc[2] + '>' + loc[1] + '</option>';
	}
	$('#location_select').html(html);
	$('#location_select').show();
};

study.displayLocationDecks = function(decks) {
	var html = '';
	for (var i = 0, j = decks.length; i < j; i++) {
		var deck = decks[i];
		var objective_calendarDays = deck[3];
		var entryCount = deck[5];
		var xstr = 'entry';
		if (entryCount != 1) {
			xstr = 'entries';
		}
		var objective_html = 'Contains ' + entryCount + ' ' + xstr + '. ';
		if (objective_calendarDays) {
			var set_on = new Date(deck[4]);
			var target_finish_date = set_on;
			target_finish_date.setDate(target_finish_date.getDate() + objective_calendarDays);
			target_finish_date = target_finish_date.toLocaleDateString();
			objective_html += 'Objective set for ' + objective_calendarDays + ' days.  Should be finished on ' + target_finish_date + '. ' + '<a href="javascript:void(0)" class="change_objective">Change objective</a>';
		} else {
			objective_html += '<a href="javascript:void(0)" class="set_objective">Set objective</a>';
		}
		objective_html = '<span style="padding-left: 10px" class="location_deck_objective">(' + objective_html + ')</span><span style="display:none" class="locationDeck_entryCount">' + entryCount + '</span>';
		html += '<tr><td><input type="checkbox" class="location_decks" value="' + deck[0] + '" ' + deck[2] + '/></td><td>' + deck[1] + objective_html + '</td></tr>';
	}
	html = '<table>' + html + '</table>';
	$('#location_decks').html(html);
	$('#location_content').show();
	$('#location_decks_message').html('Select the decks that you want to study from this location.');
};

study.locationOnchange = function(e) {
	e.preventDefault();
	var d = {}
	d.locationKey = study.getSelectedValue('#location_select');
	if (d.locationKey) {
		$.astound_ajax({'url': '/preferences/display_location_decks.json', 'dataType': 'json', 'data': d, 'success': function(json,txtStatus) {
				study.displayLocationDecks(json.decks);
			}
		});
	} else {
		$('#location_decks').html('');
		$('#location_content').hide();
	}
	return false;
};

study.displayAddLocationDialog = function(e) {
	var gm = $('#genericModal');
	var html = '<p>Enter the name for this location:</p><input type="text" id="new_location" style="width:380px"></input> <span class="button" id="confirm_location_btn">Send</span>';
	gm.hide().html(html);
	gm.dialog({'autoOpen': false, 'title': 'New Location', 'width': 460}).dialog('open');
};
study.savePreferences_handler = function(e) {
	e.preventDefault();
	var d = {};
	d.displayTagColumn = $("input:radio[name=displayTagColumn]:checked").val();
	d.displayName = $('#displayName').val();
	d.orientation = $("input:radio[name=orientation]:checked").val();
	d.allowAdvertising = $("input:radio[name=allow_advertising]:checked").val();
	d.gender = $("input:radio[name=gender]:checked").val();
	d.birthYear = $('#birth_year option:selected').val();
	var pluginPassword = $('#pluginPassword').val();
	pluginPassword = pluginPassword.replace(/^\s+/,'');
	pluginPassword = pluginPassword.replace(/\s+$/,'');
	if (pluginPassword.length > 0) {
		// User want to change the password for the plugin
		if (pluginPassword.length <= 3) {
			study.notify('Error','Password must contain at least 4 characters');
			return false;
		}
		d.pluginPassword = pluginPassword;
	}
	var url = study.baseURL + '/preferences/save.json';
	$.astound_ajax({'url': url, 'type': 'POST', 'data': d, 'success': function(json,txtStatus) {
		study.notify('Information','Your preferences were updated successfully!');
	}});

	return false;
};

study.menuDeleteDeck_confirm_handler = function(e) {
	e.preventDefault();
	var gm = $('#genericModal');
	gm.dialog('destroy');
	var setKeys = new Array();
	var setKey = study.getHiddenSetKey();
	setKeys.push(setKey);
	var data = {};
	data.setKeys = setKeys;
	var library_delete_not_authored_url = study.baseURL + '/library/delete_authored_decks.json';
	$.astound_ajax({'url': library_delete_not_authored_url, 'type': 'POST', 'data': data, 'success': function(json,txtStatus) {
		study.notify('Attention','Deck removed.');
		gm.dialog({'close': function(){ window.location.reload(); }});
	}});
	return false;
};

study.menuDeleteDeckLink_clickHandler = function(e) {
	e.preventDefault();
	var setKey = study.getHiddenSetKey();
	var message = '';
	if (study.entryCount) {
		message = 'This deck has ' + study.entryCount + ' card(s).  ';
	}
	message = message + 'Are you sure that you want to delete this deck?';
	study.confirm('Attention',message,study.menuDeleteDeck_confirm_handler);
	return false;
};

study.warnDeleteNonEmptyDecks_handler = function(e) {
	var entryCount = $(this).parent().parent().find('.authoredDecksEntryCount').text();
	if (entryCount > 0) {
		if ($(this).is(':checked')) {
			study.notify('Attention','This deck is not empty.  If you do not want to delete this deck, please unselect this deck.');
		}
	}
};
study.deleteEntries_clickHandler = function(e) {
	e.preventDefault();
	var setKey = study.getHiddenSetKey();
	var checkboxes = $('input.entrySelectCheckbox:checked');
	var data = {};
	var entryKeys = new Array();
	if (checkboxes.length > 0) {
		checkboxes.each(function() {
				var entryKey = $(this).val();
				entryKeys.push(entryKey);
		});
		data.entryKeys = entryKeys;
		data.setKey = setKey;
		var delete_cards_url = study.baseURL + '/delete_cards.json';
		$.astound_ajax({'url': delete_cards_url, 'type': 'POST', 'data': data, 'success': function(json,txtStatus) {
			checkboxes.parent().parent().remove();
			var thelist = $('#thelist');
			var count = thelist.find('td.questionColumn').length;
			if (count == 0) {
				$('#thelistContainer').hide();
			}
		}});
	} else {
		study.notify('Attention','You did not select any cards.');
	}
	return false;
};

study.library_delete_authored_decks_click_handler = function(e) {
	e.preventDefault();
	var checkboxes = $('.authored_checkbox').filter(':checked');
	if (checkboxes.length == 0) {
		study.notify('Attention','You did not select any deck.');
	} else {
		var decks = '';
		var active_decks = false;
		checkboxes.each(function() {
			var title = $(this).parent().parent().find('.library_authored_decks').text();
			decks = decks + '<li>' + title + '</li>';
			if ($(this).parent().parent().find('.LibraryStatus').hasClass('Following')) {
				active_decks = true;
			}
		});
		var message = '<p>You are about to delete decks (which you previously created). Selected decks:';
		if (active_decks) {
			message = message + ' (you are currently following some of these selected decks)';
		}
		message = message + ':</p><ul>' + decks + '</ul>';
		message = message + '<p>Are you sure you want to delete selected decks?</p>';

		study.confirm('Attention',message,study.library_delete_authored_decks_confirmed);
	}
	return false;
};

study.library_delete_not_authored_decks_click_handler = function(e) {
	e.preventDefault();
	var checkboxes = $('.not_authored_checkbox').filter(':checked');
	if (checkboxes.length == 0) {
		study.notify('Attention','You did not select any deck.');
	} else {
		var decks = '';
		var active_decks = false;
		checkboxes.each(function() {
			var title = $(this).parent().parent().find('.library_not_authored_decks').text();
			decks = decks + '<li>' + title + '</li>';
			if ($(this).parent().parent().find('.LibraryStatus').hasClass('Following')) {
				active_decks = true;
			}
		});
		var message = '<p>Selected decks';
		if (active_decks) {
			message = message + ' (you are currently following some of these selected decks)';
		}
		message = message + ':</p><ul>' + decks + '</ul>';
		message = message + '<p>Are you sure you want to remove selected decks from this page completely?</p>';

		study.confirm('Attention',message,study.library_delete_not_authored_decks_confirmed);
	}
	return false;
};

study.library_delete_authored_decks_confirmed = function(e) {
	var gm = $('#genericModal');
	gm.dialog('destroy');
	var checkboxes = $('.authored_checkbox').filter(':checked');
	var data = {};
	var setKeys = new Array();
	checkboxes.each(function() {
		var setKey = $(this).parent().parent().find('.library_hidden_setKey').text();
		setKeys.push(setKey);
	});
	data.setKeys = setKeys;
	var library_delete_not_authored_url = study.baseURL + '/library/delete_authored_decks.json';
	$.astound_ajax({'url': library_delete_not_authored_url, 'type': 'POST', 'data': data, 'success': function(json,txtStatus) {
		checkboxes.parent().parent().remove();
		study.notify('Attention','Decks removed.');
		gm.dialog({'close': function(){ window.location.reload(); }});
	}});
};

study.library_delete_not_authored_decks_confirmed = function(e) {
	var gm = $('#genericModal');
	gm.dialog('destroy');
	var checkboxes = $('.not_authored_checkbox').filter(':checked');
	var data = {};
	var setKeys = new Array();
	checkboxes.each(function() {
		var setKey = $(this).parent().parent().find('.library_hidden_setKey').text();
		setKeys.push(setKey);
	});
	data.setKeys = setKeys;
	var library_delete_not_authored_url = study.baseURL + '/library/delete_not_authored_decks.json';
	$.astound_ajax({'url': library_delete_not_authored_url, 'type': 'POST', 'data': data, 'success': function(json,txtStatus) {
		checkboxes.parent().parent().remove();
		study.notify('Attention','Decks removed.');
		gm.dialog({'close': function(){ window.location.reload(); }});
	}});
};

study.library_toggle_following_status_handler = function(e) {
	e.preventDefault();
	var el = $(this);
	var setKey = el.parent().find('span.library_hidden_setKey').text();
	var data = {};
	data.setKey = setKey;
	var tooltip_id = el.attr('id') + '_tooltip';
	var tooltip = $('#' + tooltip_id);
	el.tooltip('hide',el);
	if (el.hasClass('Following')) {
		var unsubscribe_link = study.baseURL + '/deck/unsubscribe_withoutsetlist.json';
		$.astound_ajax({'url': unsubscribe_link, 'type': 'POST', 'data': data, 'success': function(json,txtStatus) {
			el.removeClass('Following');
			el.find('img').attr('src','/images/status_gray.png');
			var sub_count_el = el.parent().parent().find('td.subscriptionCount');
			var sub_count = parseInt(sub_count_el.text()) - 1;
			sub_count_el.text(sub_count);
			var w = tooltip.width();
			var h = tooltip.height();
			tooltip.width(w);
			tooltip.html('You are no longer following this deck.  Click on the gray icon to follow this deck again.');
		}});
	} else {
		var subscribe_link = study.baseURL + '/deck/subscribe_withoutsetlist.json';
		$.astound_ajax({'url': subscribe_link, 'type': 'POST', 'data': data, 'success': function(json,txtStatus) {
			el.addClass('Following');
			el.find('img').attr('src','/images/status_green.png');
			var sub_count_el = el.parent().parent().find('td.subscriptionCount');
			var sub_count = parseInt(sub_count_el.text()) + 1;
			sub_count_el.text(sub_count);
			tooltip.html('You are now following this deck.');
		}});
	}
	el.tooltip('show',el);
	return false;
};

study.library_create_tooltip_deck_link = function() {
	var el = $(this);
	var tooltip = '';
	var status_el = el.parent().parent().find('.LibraryStatus');
	if (status_el.hasClass('Following')) {
		tooltip = 'Take me to this deck.';
	} else {
		tooltip = 'You are not studying / following this deck.  Click to study this deck.';
	}
	var need_tooltip_id = el.attr('id');
	var tooltip_id = need_tooltip_id + '_tooltip';
	var tooltip_el = $('#' + tooltip_id);
	if (tooltip_el.length == 0) {
		tooltip_el = $('<div id="' + tooltip_id + '"/></div>');
		tooltip_el.html(tooltip);
		tooltip_el.hide();
		$('body').append(tooltip_el);
		$.fn.tooltip.map[need_tooltip_id] = {
			'position': 'right',
			'verticalAlignment': 'middle',
			'useSpeechBubble': true
		};
	} else {
		tooltip_el.html(tooltip);
	}
};
study.library_create_tooltip_element_handler = function(e) {
	e.preventDefault();
	var el = $(this);
	var tooltip = '';
	if (el.hasClass('Following')) {
		tooltip = 'You are currently studying / following this deck.';
	} else {
		tooltip = 'You are not studying / following this deck.';
	}
	var need_tooltip_id = el.attr('id');
	var tooltip_id = need_tooltip_id + '_tooltip';
	var tooltip_el = $('#' + tooltip_id);
	if (tooltip_el.length == 0) {
		tooltip_el = $('<div id="' + tooltip_id + '"/></div>');
		tooltip_el.html(tooltip);
		tooltip_el.hide();
		$('body').append(tooltip_el);
		$.fn.tooltip.map[need_tooltip_id] = {
			'position': 'left',
			'verticalAlignment': 'middle',
			'useSpeechBubble': true
		};
	}
	return false;
};

study.do_nothing_handler = function(e) {
	e.preventDefault();
	return false;
};

study.make_tooltip_element = function() {
	// For elements that need tooltip, but the tooltip element does not already exist in the DOM, create the tooltip element using the title attribute
	var need_tooltip_el = $(this);
	var need_tooltip_id = need_tooltip_el.attr('id');
	var tooltip_id = need_tooltip_id + '_tooltip';
	var tooltip_el = $('#' + tooltip_id);
	if (tooltip_el.length == 0) {
		tooltip_el = $('<div id="' + tooltip_id + '"></div>');
		var title = need_tooltip_el.attr('title');
		tooltip_el.hide().html(title);
		$('body').append(tooltip_el);
	}
	need_tooltip_el.attr('title','');
};

study.search_result_update_tooltip_handler = function(e) {
	e.preventDefault();
	var p = $(this);
	var library_el = p.find('.LibraryStatus');
	if (library_el.hasClass('InLibrary')) {
		var tooltip_id = p.find('.resubscribe_link').attr('id') + '_tooltip';
		var tooltip_el = $('#' + tooltip_id);
		tooltip_el.html('Take me to this deck.');
	} else {
		var tooltip_id = p.find('.resubscribe_link').attr('id') + '_tooltip';
		var tooltip_el = $('#' + tooltip_id);
		tooltip_el.html('Add this deck to my library.');
	}
	return false;
};

study.showFloatingTagTable = function() {
	if (study.floating_tag_table_visible) {
		return true;
	}
	$('#tagTableDiv').appendTo('#floatingTagsDivOuter');
	var w = Math.floor(jQuery(window).width() / 2);
	var h = Math.floor(jQuery(window).height() / 2);
	$('#floatingTagsDivOuter').dialog({
			'modal': false, 
			'closeOnEscape': true, 
			'height': h, 
			'width': w, 
			'title': 'Tags', 
			'dialogClass': 'dialogFixed',
			'close': study.hideFloatingTagTable
			});
	study.floating_tag_table_visible = true;
};

study.hideFloatingTagTable = function() {
	$('#tagTableDiv').insertAfter('#tagTableHeader');
	study.floating_tag_table_visible = false;
};

study.reload = function() {
	window.location.href = study.baseURL;
};

study.display_unsubscribe_modal = function() {
	var url = $('#unsubscribe_link').attr('href') + '?setKey=' + study.getHiddenSetKey();
	$.astound_ajax({'url': url, 'type': 'GET', 'dataType': 'html', 'async': false, 'success': function(html,textStatus){
		var gm = $('#genericModal');
		gm.hide().html(html);
		gm.dialog({'autoOpen': false, 'title': 'Warning', 'width': 460}).dialog('open');
	}});
};

study.display_unsubscribe_confirmed_modal = function() {
	var url = $('#unsubscribe_confirmed').attr('href');
	$.astound_ajax({'url': url, 'type': 'GET', 'dataType': 'html', 'async': false, 'success': function(html,textStatus){
		var gm = $('#genericModal');
		gm.dialog('option', 'close', function() { window.location.href = study.baseURL; });
		gm.html(html);
		//gm.hide().html(html);
		//gm.dialog({'autoOpen': false, 'title': 'Warning', 'width': 460}).dialog('open');
	}});
};

study.display_share_modal = function() {
	var url = $('#menu_share').attr('href') + '?setKey=' + study.getHiddenSetKey();
	$.astound_ajax({'url': url, 'type': 'GET', 'dataType': 'html', 'async': false, 'success': function(html,textStatus){
		var gm = $('#genericModal');
		gm.hide().html(html);
		var u = study.cached_deck_list.shortUrl;
		$('#shareURL_span').html('<a href="' + u + '">' + u + '</a>');
		gm.dialog({'autoOpen': false, 'title': 'Sharing', 'width': 460}).dialog('open');
	}});
};

study.display_study_materials_modal = function() {
	var w = Math.floor(jQuery(window).width() / 2);
	var h = Math.floor(jQuery(window).height() / 2);
	var url = $('#menu_study_materials').attr('href') + '?setKey=' + study.getHiddenSetKey();
	$.astound_ajax({'url': url, 'type': 'GET', 'dataType': 'html', 'async': false, 'success': function(html,textStatus){
		var gm = $('#genericModal');
		gm.hide().html(html);
		var u = study.cached_deck_list.shortUrl;
		$('#shareURL_span').html('<a href="' + u + '">' + u + '</a>');
		gm.dialog({'autoOpen': false, 'title': 'Study Materials', 'width': w, 'height': h}).dialog('open');
	}});
};

study.display_edit_deck = function() {
	var url = $('#menu_edit_deck').attr('href') + '?setKey=' + study.getHiddenSetKey();
	window.location.href = url;
};

study.display_deck_feedback_page = function() {
	var url = $('#menu_feedback').attr('href') + '?setKey=' + study.getHiddenSetKey();
	window.location.href = url;
};

study.display_contributors_modal = function() {
	var w = Math.floor(jQuery(window).width() / 2);
	var h = Math.floor(jQuery(window).height() / 2);
	var url = $('#menu_contributors').attr('href') + '?setKey=' + study.getHiddenSetKey();
	$.astound_ajax({'url': url, 'type': 'GET', 'dataType': 'html', 'async': false, 'success': function(html,textStatus){
		var gm = $('#genericModal');
		gm.hide().html(html);
		gm.dialog({'autoOpen': false, 'title': 'Contributors', 'width': w, 'height': h}).dialog('open');
	}});
};

study.library_deck_link_click_handler = function(e) {
	e.preventDefault();
	var el = $(this);
	var library_el = el.parent().parent().find('.LibraryStatus');
	if (library_el.hasClass('Following')) {
		var setKey = el.parent().parent().find('.library_hidden_setKey').text();
		window.location.href = study.baseURL + '/set/study.html?setKey=' + setKey;
	} else {
		var subscribe_link = el.attr('href');
		$.astound_ajax({'url': subscribe_link, 'type': 'POST', 
			'success': function(json,txtStatus) { 
				study.cached_deck_list = json; 
				library_el.addClass('Following');
				library_el.find('img').attr('src','/images/status_green.png');
				var need_tooltip_id = el.attr('id');
				var tooltip_id = need_tooltip_id + '_tooltip';
				var tooltip_el = $('#' + tooltip_id);
				tooltip_el.html('You are now following this deck.  Click again to go to this deck.');
			}
		});
	}
	return false;
};

study.search_result_resubscribe = function(e) {
	e.preventDefault();
	var el = $(this);
	var library_el = el.parent().parent().find('.LibraryStatus');
	if (library_el.hasClass('InLibrary')) {
		var setKey = el.parent().parent().find('.search_result_hidden_setKey').text();
		window.location.href = study.baseURL + '/set/study.html?setKey=' + setKey;
	} else {
		var subscribe_link = el.attr('href');
		$.astound_ajax({'url': subscribe_link, 'type': 'POST', 
			'success': function(json,txtStatus) { 
				study.cached_deck_list = json; 
				library_el.addClass('InLibrary');
				library_el.find('img').attr('src','/images/status_green.png');
				var need_tooltip_id = el.attr('id');
				var tooltip_id = need_tooltip_id + '_tooltip';
				var tooltip_el = $('#' + tooltip_id);
				tooltip_el.html('Added to libary.  Click again to go to this deck.');
			}
		});
	}
	return false;
};

study.resubscribe = function(e) {
	e.preventDefault();
	var subscribe_link = $(this).attr('href');
	$(this).parent().html("Added to your library");
	$.astound_ajax({'url': subscribe_link, 'type': 'POST', 'success': function(json,txtStatus) { study.cached_deck_list = json; }});
	return false;
};

study.fetchTemplate = function(templateName) {
	if (typeof(study.templates) == 'undefined') {
		study.templates = {};
	}
	if (study.templates[templateName]) {
		return study.templates[templateName];
	}
	var file = '/ajax/' + templateName + '.html';
	$.astound_ajax({'url': file, 'type': 'GET', 'dataType': 'html', 'async': false, 'success': function(html,textStatus){
	    study.templates[templateName] = html;
	}});
	return study[templateName];
};

study.search = function(e) {
	e.preventDefault();
	$('#search_form').submit();
	return false;
};

study.displayMsg = function(type,msg) {
    if (type == 'error') {
	$('#mesgArea').html('<span class="error">' + msg + '</span>').removeClass('hideMe');
    } else {
	$('#mesgArea').html('<span class="mesg">' + msg + '</span>').removeClass('hideMe');
    }
};

study.renderAddSetForm = function(e) {
	e.preventDefault();
	study.removeEditors();
	$('#currentDeck').html('You are creating a new deck:');
	$("#content").astound_ajax_load('/ajax/set/newform.html',{},function(){
		$("#submit").click(study.submitAddSetForm);
		study.addClickHandlerForSets();
		study.addEditors();
	});
	return false;
};

study.sendFeedback = function(e) {
	e.preventDefault();
	var feedback = study.getEditorContent('feedbackEditor');
	var setKey = study.cached_deck_list.setKey;
	var email = $('#email').val();
	var data = {'feedback': feedback, 'setKey': setKey};
	if ((typeof(email) != 'undefined') && (email != '')) {
		data.email = email;
	}
	$.astound_ajax({'url': '/set/sendFeedback.json', 'type': 'POST', 'dataType': 'json', 'data': data, 'async': false, 'success': function(json,txtStatus){
			var w = Math.floor(jQuery(window).width() / 2);
			var h = Math.floor(jQuery(window).height() / 2);
			$('#genericModal').hide().html('Your feedback was sent successfully!').dialog({'autoOpen': false, 'modal': true, 'close': study.reload, 'title': 'Information', 'width': w, 'height': h}).dialog('open');
		}
	});
	return false;
};

study.sendOurFeedback = function(e) {
	e.preventDefault();
	var ourFeedback = study.getEditorContent('ourFeedback');
	var email = $('#email').val();
	var data = {'ourFeedback': ourFeedback};
	if ((typeof(email) != 'undefined') && (email != '')) {
		data.email = email;
	}
	$.astound_ajax({'url': '/ourFeedback/send.json', 'type': 'POST', 'dataType': 'json', 'data': data, 'async': true});
	study.removeEditors();
	$('textarea.loadEditor').remove();
	$(this).val('Feedback sent!').disable();
	var reload = $('<input type="button" value="Display Set"/>');
	reload.click(study.reloadCurrentSet);
	reload.insertAfter(this);
	return false;
};

study.isLoggedIn = function() {
	if ($('#topmenu').length == 1) {
		return true;
	} else {
		return false;
	}
};
study.displayPage = function(e) {
	e.preventDefault();
	var href = $(this).attr('href');
	study.removeEditors();
	var callback = function() {};
	if (href.search(/Feedback/) >= 0) {
		$('#content').html(study.fetchTemplate('ourFeedback'));
		study.addEditors();
		$('#ourFeedback_sendBtn').click(study.sendOurFeedback);
	} else if (href.search(/faq\.html/) >= 0) {
		$('#content').html(study.fetchTemplate('faq'));
		$(".stripeMe tr:nth-child(even)").addClass("alt");
	} else if (href.search(/tos\.html/) >= 0) {
		$('#content').html(study.fetchTemplate('tos'));
	} else if (href.search(/contact\.html/) >= 0) {
		$('#content').html(study.fetchTemplate('contact'));
	}
	$('#content').find('[href="/faq.html"]').click(study.displayPage);
	if (study.isLoggedIn()) {
		$('#content').find('[href="/"]').click(function(e) { e.preventDefault(); study.displayEditEntriesAndStudyPage(); return false;});
	}
	$('#content').find('[href="/contact.html"]').click(study.displayPage);
	if ($('#topmenu').length == 1) {
		$('#topmenu').scrollIntoView();
	}
	return false;
};

study.submitAddSetForm = function(e) {
	e.preventDefault();
	$('#addsetform').submit();
	/*
	var selectedIndex = $("#visibility").attr('selectedIndex');
	var sel = $("#visibility").get(0);
	var visibility = sel.options[selectedIndex].value;
	var title = $('#title').val();
	if (title.search(/\S/) == -1) {
		study.error('#title','Title is missing.');
		return false;
	}
	$(this).text('Please wait');
	var materials = study.getEditorContent('materials');
	var description = study.getEditorContent('description');
	var data = {'title': title, 'visibility': visibility, 'materials': materials, 'description': description}
	var em = $('#email');
	if (em.length == 1) {
		var email = em.val();
		if ((typeof(email) != 'undefined') && (email != '')) {
			data.email = email;
		}
	}
	$.astound_ajax({'url': '/set/add.json', 'type': 'POST', 'dataType': 'json', 'data': data, 'async': false, 'success': function(json,textStatus){
			window.location.href = "/";
		}
	});
	*/
	return false;
};

study.error = function(selector,msg) {
	$('<div class="error">' + msg + '</div>').insertBefore(selector);
};

study.thelist_click_handler = function(e) {
	if (e.ctrlKey) {
		var cell = $(e.target);
		while (cell.parent().parent().parent().attr('id') != 'thelist') {
			cell = cell.parent();
		}
		var row = cell.parent();
		if (typeof(study.reorderEntry) == 'undefined') {
			study.reorderEntry = row;
		} else {
			// Put the first entry selected after the second entry
			var data = {}
			data.setKey = study.getHiddenSetKey();
			data.entryKey1 = study.reorderEntry.find('.contributorColumn').find('.entryKey').text();
			data.entryKey2 = row.find('.contributorColumn').find('.entryKey').text();
			$.astound_ajax({'url': '/set/reorderEntries.json',
					'type': 'POST', 'dataType': 'json', 'async': false, 'data': data, 
					'success': function(json,textStatus) {
					study.reorderEntry.insertAfter(row);
					delete(study.reorderEntry);
			}});
		}
	}
};

study.renderTagList = function() {
	$('#taglist').html('').append('<option value="+">Please select a tag.</option><option value="-">Entries with no tags</option><option value="^">Entries marked not appropriate for plugin</option>');
	var tags = study.tags;
	for (var i = 0, j = tags.length; i < j; i++) {
		var t = $('<option></option>');
		t.val(tags[i]);
		t.text(tags[i]);
		t.appendTo('#taglist');
	}
};

study.entriesSearch_listView = function(e) {
	e.preventDefault();
	$(this).disable().val('Searching');
	var tag = study.getSelectedValue('#taglist');
	var searchTerm = '';
	var setKey = study.getHiddenSetKey();
	if ( $('#entries_search').length > 0) {
		searchTerm = $('#entries_search').val(); 
	}
	var data = {'searchTerm': searchTerm, 'tag': tag, 'setKey': setKey};
	$('#thelistContainer').astound_ajax_load('/ajax/set/listViewSearch.html',data, function() {
		var thelist = $('#thelist');
		thelist.removeClass('being_used_but_hidden');
		thelist.find('.draggable').astound_draggable();
		thelist.find('tr').astound_droppable(study.addTagToEntry);
		var count = thelist.find('td.questionColumn').length;
		if (count == 0) {
			$('#thelistContainer').hide();
		} else {
			$('#thelist').removeClass('being_used_but_hidden');
			$('#thelistContainer').show();
		}
		$('#entries_search_result').html('Found: ' + count);
		$(".stripeMe tr:nth-child(even)").addClass("alt");
		$('#entries_search_btn').val('Search').enable();
		$('#selectAll').click(study.selectAll);
		if (study.isContributor) {
			$('.tagColumn').removeClass('being_used_but_hidden');
			$('.contributorColumn').removeClass('being_used_but_hidden');
		}
		study.showOrHideTheListFooter();
	});
	return false;
};

study.selectAll = function(e) {
	$('.entrySelectCheckbox').click();
};

study.help_link_click_handler = function(e) {
	e.preventDefault();
	var help = study.fetchTemplate('help');
	var w = Math.floor(jQuery(window).width() / 2);
	var w = 620;
	var h = Math.floor(jQuery(window).height() / 2);
	var h = 423;
	var gm = $('#genericModal');
	gm.hide().html(help);
	gm.dialog({'autoOpen': false, 'title': 'Quick Help', 'width': w, 'height': h}).dialog('open');
	return false;
}
study.doNothing_handler = function(e) {
	e.preventDefault();
	return false;
};

study.renderTemplate = function(templateName,id) {
	var html = study.fetchTemplate(templateName);
	$('#' + id).html(html);
};

study.notify = function(title,message,options) {
	var w = Math.floor(jQuery(window).width() / 2);
	var h = Math.floor(jQuery(window).height() / 2);
	if (options) {
		w = options.width ? options.width : w;
		h = options.height ? options.height : h;
	}
	var gm = $('#genericModal');
	gm.hide().html(message);
	gm.dialog({'autoOpen': false, 'title': title, 'width': w, height: h, 'modal': true}).dialog('open');
};

/*
 * closeNotification is used to close existing notification.
 * This function can be invoked anywhere.
 */
study.closeNotification = function() {
	var gm = $('#genericModal');
	gm.dialog('close');
};

/*
 * dialog_cancel is used as an event handler for the Cancel button in a 
 * confirmation dialog.
 */
study.dialog_cancel = function(e) {
	$(this).dialog('close');
};

study.confirm = function(title,message,confirm_handler) {
	var w = Math.floor(jQuery(window).width() / 2);
	var h = Math.floor(jQuery(window).height() / 2);
	var gm = $('#genericModal');
	gm.hide().html(message);
	gm.dialog({'autoOpen': false, 'title': title, 'width': w, buttons: {'Confirm': confirm_handler, 'Cancel': this.dialog_cancel}}).dialog('open');
};

study.addTag = function(e) {
	e.preventDefault();
	$('#newTag_btn').attr('value','Processing').disable();
	var setKey = study.getHiddenSetKey();
	var newTag = $('#newTag_input').val();
	if ((newTag == undefined) || (newTag.search(/\S/) == -1) || (newTag == '-') || (newTag == '+')) {
		$('#newTag_btn').enable().val('Add Tag');
		study.notify('Attention','Please enter a valid tag.');
		return false;
	}
	var data = {'setKey': setKey, 'tag': newTag };
	$.astound_ajax({'url': '/tag/add.json', 'type': 'POST', 'dataType': 'json', 'async': false, 'data': data, 'success': function(json,textStatus) {
			var tag = $('#newTag_input').val();
			var node;
			if ($('#floatingTagsDivInner').find('#tagTableDiv').length == 1) {
				/* If the tag table is currently floating (being used to tag existing entries), hide the checkbox, and don't check the checkbox */
				node = $('<tr><td class="tagTable"><input type="checkbox" name="tag" class="tag_input hideMe" value="' + tag + '"/><span class="draggable">' + tag + '</span></td></tr>');
				node.insertBefore('#newTag_tr');
			} else {
				node = $('<tr><td class="tagTable"><input type="checkbox" name="tag" class="tag_input" value="' + tag + '"/><span class="draggable">' + tag + '</span></td></tr>');
				node.insertBefore('#newTag_tr');
				if (! study.floating_tag_table_visible) {
					node.find('.tag_input').click();
				}
			}
			node.find('.draggable').astound_draggable();
			$('#newTag_input').val('');
			$('#newTag_btn').val('Add Tag').enable();
			study.tags = json.tags;
			study.renderTagList();
		}
	});
	return false;
};

study.deleteTagFromEntry = function(draggable) {
	var tag = draggable.text();
	var contributorColumn = draggable.parent().next();
	var setKey = contributorColumn.find('.setKey').text();
	var entryKey = contributorColumn.find('.entryKey').text();
	var data = {'setKey': setKey, 'entryKey': entryKey, 'tag': tag};
	$.astound_ajax({'url': '/entry/deleteTag.json', 'type': 'POST', 'dataType': 'json', 'data': data, 'async': false, 'success': function(json,textStatus){
		var siblingBreak = draggable.next();
		draggable.remove();
		siblingBreak.remove();
	}});
};

study.getHiddenSetKey = function() {
	return $('#hidden_setKey').text();
};

study.addTagToEntry = function(event,ui,dropTargetRow) {
	var draggable = ui.draggable;
	var tag = draggable.text();
	if (draggable.parents('#thelist').length == 1) {
		// code to check if the tag was dragged and dropped on the same row
		if (draggable.parent().parent() == dropTargetRow) {
			var x = 0;
		}
	}
	// Check to see if the entry has this tag already
	var tags = dropTargetRow.find('.tagColumn').find('span');
	for (var i = 0, j = tags.length; i < j; i++) {
		if ($(tags[i]).text() == tag) {
			return;
		}
	}

	var data = {};
	data.entryKey = dropTargetRow.find('.entryKey').text();
	data.setKey = study.getHiddenSetKey();
	data.tag = tag;
	$.astound_ajax({'url': '/entry/addTag.json', 'type': 'POST', 'dataType': 'json', 'data': data, 'async': false, 'success': function(json,textStatus){
		dropTargetRow.find('.tagColumn').append('<span class="newTag">' + tag + '</span><br>');
		var newTag = dropTargetRow.find('.tagColumn').find('.newTag');
		newTag.addClass('draggable').removeClass('newTag');
		newTag.astound_draggable();
	}});
};

study.deleteTags = function() {
	var setKey = study.getHiddenSetKey();
	var tags = new Array();
	$('#tagTableDiv').find('input:checked').each(function() { tags.push($(this).val());});
	if (tags.length == 0) {
		study.notify('Attention',"Please select tags that you want to delete.");
	} else {
		var data = {'setKey': setKey, 'tags': tags };
		$.astound_ajax({'url': '/tags/delete.json', 'type': 'POST', 'dataType': 'json', 'data': data, 'async': false, 'success': function(json,textStatus){
				study.tags = json.tags;
				study.renderTagTable();
				study.renderTagList();
		}});
	}
};

study.deleteTag = function(event,ui) {
	var draggable = ui.draggable;
	if (draggable.parents('#thelist').length == 1) {
		// The thing being dragged is a tag associated with an entry, so the user wants to remove this tag from the associate entry
		study.deleteTagFromEntry(draggable);
	} else {
		var tag = draggable.text();
		draggable.parent().parent().addClass('removeMe').hide();
		var setKey = study.getHiddenSetKey();
		var data = {'setKey': setKey, 'tag': tag };
		$.astound_ajax({'url': '/tag/delete.json', 'type': 'POST', 'dataType': 'json', 'data': data, 'async': false, 'success': function(json,textStatus){
			study.tags = json.tags;
			study.renderTagList();
		}});
	}
	event.preventDefault();
	return false;
};

study.renderTagTable = function(tags_json,selector) {
	if (typeof(selector) == 'undefined') { selector = '#tagTableDiv'; }
	$(selector).html('');
	var node = $('<table></table');
	var tags = study.tags || new Array();
	for (var i = 0, j = tags.length; i < j; i++) {
		var tag = tags[i];
		if ((tag != "+") && (tag != '-')) {
			node.append('<tr><td class="tagTable"><input type="checkbox" name="tag" class="tag_input" value="' + tag + '"/><span class="draggable">' + tag + '</span></td></tr>');
		}
	}
	node.append('<tr id="newTag_tr"><td><input type="text" id="newTag_input"/>&nbsp;<span class="button" id="newTag_btn">Add tag</span>&nbsp;<span class="button deleteTagBtn" id="deleteTags">Delete selected tags</span></td></tr>');
	node.appendTo(selector);
	$('#newTag_btn').click(study.addTag);
	if (typeof(tags_json) != 'undefined') {
		var nodes = $(selector).find('.tag_input');
		for(var i = 0, j = nodes.length; i < j; i++) {
			node = $(nodes.get(i));
			var tag = node.val();
			if (tags_json[tag]) {
				node.click();
			}
		}
	}
	$(selector).find('#deleteTags').click(study.deleteTags);
	$(selector).find('.draggable').astound_draggable();
	$('.tag_delete').astound_droppable(study.deleteTag);
	study.astound_adjustHeight();
};

study.removeContentOfOtherTabs = function() {
    var map = {};
    map['List View'] = 'listViewContainerDiv';
    map['Study View'] = 'studyViewContainerDiv';
    map['Unsubscribe'] = 'unsubscribeContainerDiv';
    map['Subscribe'] = 'subscribeContainerDiv';
    map['Feedback / Contact'] = 'feedbackContainerDiv';
    map['Study Materials'] = 'studyMaterialsContainerDiv';
    map['Edit'] = 'editTabContainer';
    map['Contributors'] = 'contributorsContainerDiv';
    for (t in map) {
	if (t != study.tabName) {
	    var id = map[t];
	    $('#' + id).html('');
	}
    }
};

study.importFileUpload = function(e) {
	e.preventDefault();
	var setKey = study.getHiddenSetKey();
	var url = '/set/import.json?setKey=' + setKey
	$.ajaxFileUpload({
		'url': url,
		'secureuri': false,
		'fileElementId': 'fileUploadField',
		'responseType': 'json',
		'success': function (data, status) { $('#importExportDivOuter').dialog('close'); study.notify('Information','File imported successfully!');},
		'error': function (data, status, e) { study.notify('Error','Sorry.  We were not able to import selected file.'); }
	});
	return false;
};

study.renderImportForm = function(hash) {
    $('#importExportDivInner').html(study.fetchTemplate('importForm'));
    hash.w.show();
    $('#fileUploadSubmit').click(study.importFileUpload);
};

study.importLinkClicked = function(e) {
	e.preventDefault();
	$('#importExportDivOuter').html(study.fetchTemplate('importForm'));
	$('#fileUploadSubmit').click(study.importFileUpload);
	var w = Math.floor(jQuery(window).width() / 2);
	var h = Math.floor(jQuery(window).height() / 2);
	$('#importExportDivOuter').dialog({'modal': true, 'height': h, 'width': w, 'title': 'Import Entries'});
	return false;
};

study.exportLinkClicked = function(e) {
	e.preventDefault();
	var setKey = study.getHiddenSetKey();
	var exportForm = $('#exportForm');
	exportForm.find('input.exportEntry').remove();
	$('#exportForm_setKey').val(setKey);
	$('input.entrySelectCheckbox:checked').each(function(){ var entryKey = $(this).val(); var inputEl = $('<input type="hidden" name="entryKey" class="exportEntry"/>'); inputEl.val(entryKey); inputEl.appendTo(exportForm);});
	exportForm.submit();
	return false;
};

study.printLinkClicked = function(e) {
	e.preventDefault();
	var setKey = study.getHiddenSetKey();
	// User should be able to select entries, and print just those selected.
	// How to do this in a pop-up window (we must do a POST)
	// We can do this by creating a hidden form (or form with no visible fields / buttons)
	// that has a target="_blank".  For each selected entry, we would create a hidden
	// field.  And then we would try to submit this form.  Not sure if this would work
	// with pop-up blocker
	var print_entries_form = $('#print_entries_form');
	print_entries_form.append('<input type="hidden" name="setKey" value="' + setKey + '"/>');
	var selectedCheckboxes = $('input.entrySelectCheckbox:checked');
	if (selectedCheckboxes.length > 0) {
		$('input.entrySelectCheckbox:checked').each(function() {
				var entryKey = $(this).val();
				print_entries_form.append('<input type="hidden" name="entryKey" value="' + entryKey + '"/>');
		});
		print_entries_form.get(0).submit();
		print_entries_form.html('');
	} else {
		study.notify('Attention','Please select entries that you wish to print.');
	}
	return false;
};

study.renderTabs = function(json,text) {
	$('#content').html(json.renderSetHTML);
	study.tags = json.tags;
	if ((study.social) && (study.socialView != 'canvas')) {
		$('ul.tabs').find('span').each(function() {
			if ( $(this).text() != 'Study View') {
				$(this).parent().parent().remove();
	    }
		});
	}
	study.tabs = $("#settabs").tabs({'collapsible': true, 'deselectable': true});
	//$('#settabs').block({'css': {'backgroundColor': 'transparent'}, 'message': null, 'overlayCSS': {'opacity': 0}}); 
	$('.ui-tabs-nav').bind('tabsselect', function(event,ui) {
		//study.tabName = '';
		//study.removeEditors();
		//study.removeContentOfOtherTabs();
		//$('#settabs').block({'css': {'background-color': 'transparent'}, 'message': null, 'overlayCSS': {'opacity': 0}}); 
	});
	$('.ui-tabs-nav').bind('tabsshow', function(event,ui) {
		//$('#settabs').unblock();
		var tabName = $(ui.tab).text();
		study.tabName = tabName;
		study.tabIndex = ui.index;
		study.uiPanel = ui.panel; // element that contains the content of the tab
		study.uiTab = ui.tab; // anchor element of the clicked tab
		study.removeContentOfOtherTabs();
		if ((! study.social) || (study.socialView == 'canvas')) {
			if ($('#footer').hasClass('hideMe')) {
				$('#footer').removeClass('hideMe');
				$('.footer').not('#showHiddenElements').click(study.displayPage);
			}
			$('#showHiddenElements').click(study.astound_adjustHeight);
		}
		var setKey = study.getHiddenSetKey();
		if (tabName == "List View") {
			$(".stripeMe tr").mouseover(function(){$(this).addClass("over");}).mouseout(function(){$(this).removeClass("over");});
			$(".stripeMe tr:nth-child(even)").addClass("alt");
			var count = $('#thelist').find('td.questionColumn').length;
			if (count == 0) {
				$('#thelistContainer').hide();
			}
			if ($('#addOrEditEntryDiv').children().length > 0) {
		    // quick hack.  If we are supposed to show the add entry div, show it completely with the tag table as well
		    study.showAddOrEditEntryDiv();
			}
			study.entryCount = parseInt($('#entryCount_all').text());
			study.showOrHideTheListFooter();
			$('#floatingTagsDivOuter').jqm({'modal': false, 'overlay': 0, 'onShow': study.moveTagTableIntoFloatingDiv, 'onHide': study.moveTagTableOutOfFloatingDiv}).jqDrag('#floatingTagsDivHandle').jqResize('.jqResize');
			$('#entries_search_form').submit(study.entriesSearch_listView);
			$('#entries_search_table').removeClass('hideMe');
			$('#entries_search_btn').click(study.entriesSearch_listView);
			$('#importLink').click(study.importLinkClicked);
			$('#exportLink').click(study.exportLinkClicked);
			$('#printLink').click(study.printLinkClicked);
		} else if (tabName == "Unsubscribe") {
			$('a', ui.panel).click(function(e) {
				e.preventDefault();
				var url = $(this).attr('href');
				$(ui.panel).astound_ajax_load(url);
				return false;
			});
		} else if (tabName == "Study View") {
			$('#entries_search_table').removeClass('hideMe');
			$('#studyViewContainerDiv').removeClass('hideMe');
			$('#start').click(study.startStudy);
			if (study.social) {
				if (study.socialView != 'canvas') {
					$('#settabs').remove();
					$('#start').click();
		    }
			}
		} else if (tabName == "Share") {
		} else if (tabName == "Feedback / Contact") {
			study.addEditors();
			$('#feedback_sendBtn').click(study.sendFeedback);
		} else if (tabName == 'Contributors') {
			$('#contributor_search_btn').click(study.search_for_potential_contributors);
			$('#remove_contributors_btn').click(study.removeContributors);
		} else if (tabName == "Edit") {
			study.addEditors();
			$("#submit").click(study.submitEditSetForm);
		}
	});
};

study.reloadCurrentTab = function(callback) {
    /*
    var t = study.tabs;
    t.tabs('load',study.tabIndex);
    */
    // var href = $('.ui-tabs-selected').find('a').attr('href');
    var href = $.data(study.uiTab, 'load.tabs');
    $(study.uiPanel).astound_ajax_load(href,{},callback);
    // $('.ui-tabs-selected').find('a').click();
};

study.removeContributors = function(e) {
    e.preventDefault();
    var setKey = study.getHiddenSetKey();
		var contributors = new Array();
    $('#current_contributors').find('input:checked').each(function() {contributors.push($(this).val());});
		var data = {'setKey': setKey, 'contributors': contributors };
    $.astound_ajax({'url': '/set/removeContributors.json',
	    'type': 'POST',
	    'dataType': 'json',
	    'async': false,
	    'data': data,
	    'success': function() {
				$('#contributorsContainerDiv').text('Contributor(s) removed successfully!');
		}
	    });
    return false;
};

study.addContributors = function(e) {
    e.preventDefault();
    var setKey = study.getHiddenSetKey();
		var contributors = new Array();
    $('#contributorSearchResult').find('input:checked').each(function() {contributors.push($(this).val());});
		var data = {'setKey': setKey, 'contributors': contributors };
    $.astound_ajax({'url': '/set/addContributors.json',
	    'type': 'POST', 
	    'dataType': 'json',
	    'async': false,
	    'data': data,
	    'success': function() {
				var gm = $('#genericModal');
				$('#contributorsContainerDiv').text('Contributor(s) added successfully!');
		}
	    });
    return false;
};

study.search_for_potential_contributors_display_results = function(data) {
	$('#contributor_search_btn').text('Search');
    if (data.users.length > 0) {
	var r = $('<table></table>');
	for (var i = 0, j = data.users.length; i < j; i++) {
	    r.append('<tr><td>' + data.users[i].displayName + '</td><td><input type="checkbox" name="contributor" value="' + data.users[i].key + '"/></td></tr>');
	}
	r.append('<tr><td colspan="2"><span class="button" id="contributor_add_btn">Allow selected users to contribute.</span></td></tr>');
	$('#contributorSearchResult').html('<form action="/" method="post" id="contributorSearchResultForm"></form>');
	r.appendTo('#contributorSearchResultForm');
    } else {
	$('#contributorSearchResult').html('<p>We did not find any user with the name or email address you specified.</p>');
    }
    $('#contributor_search_btn').val('Search').enable();
};

study.search_for_potential_contributors = function(e) {
    e.preventDefault();
		//debugger;
    var nameOrEmail = $('#nameOrEmail').val();
    var setKey = study.getHiddenSetKey();
    $(this).text('Please wait!').disable();
    $.astound_ajax({'url': '/set/searchForPotentialContributors.json',
	    'type': 'POST', 
	    'dataType': 'json',
	    'async': false,
	    'data': {'setKey': setKey, 'nameOrEmail': nameOrEmail},
	    'success': study.search_for_potential_contributors_display_results
	    });
    return false;
};

study.getSelectedValue = function(selector) {
    var selectedIndex = $(selector).attr('selectedIndex');
    var sel = $(selector).get(0);
    var val = sel.options[selectedIndex].value;
    return val;
};

study.getSelectedOption = function(selector) {
    var selectedIndex = $(selector).attr('selectedIndex');
    var sel = $(selector).get(0);
    var selectedOption = sel.options[selectedIndex];
    return $(selectedOption);
};

study.startStudy = function(e) {
    e.preventDefault();
		/*
		 * In the study view, we allow the user to search for related entries.
		 * We also allow the user to add new entries.  When the user add new
		 * entries in the study view, only these new entries should be displayed.
		 * Therefore, any search results that were done before the user click on the Study
		 * button should be removed from the DOM.
		 */
		$('.thelist_entries').remove();
    var tag = study.getSelectedValue('#taglist');
    var setKey = study.getHiddenSetKey();
    $(this).val('Please wait!').disable();

    $.astound_ajax({'url': '/set/study.json',
	    'type': 'POST', 
	    'dataType': 'json',
	    'async': false,
	    'data': {'setKey': setKey, 'tag': tag},
	    'success': study.renderSetEntries
	    });
    return false;
};

study.setlistUp = function(e) {
    e.preventDefault();
    $('#setlist_select').blur();
    $('#setlist_select').change();
    return false;
};

study.setlistChange = function(e) {
    e.preventDefault();
    var value = study.getSelectedValue('#setlist_select');
    $('#hidden_setKey').text(value);
    study.removeEditors();
    $.astound_ajax({'url': '/set/render.json', 'dataType': 'json', 'data': {'setKey': value}, 'success': study.renderTabs});
    $('.setlist_currentlySelected').unbind('mouseup').removeClass('.setlist_currentlySelected');
    var option = study.getSelectedOption('#setlist_select');
    option.mouseup(study.setlistUp).addClass('setlist_currentlySelected');
    return false;
};

study.reloadCurrentSet = function(e) {
    e.preventDefault();
    var value = study.getHiddenSetKey();
    study.removeEditors();
    $.astound_ajax({'url': '/set/render.json', 'dataType': 'json', 'data': {'setKey': value}, 'success': study.renderTabs});
    return false;
};

study.log = function(msg) {
    if (typeof(window.console) != 'undefined') {
			console.log(msg);
    }
};

study.handle_removeDeckMenu = function(e) {
	// It is strange.  The mouseout event is triggered on the parent element when we mouseover a child element.
	// Not sure what is going on.  This code check for this condition.
	var relatedTarget = $(e.relatedTarget);
	if (relatedTarget.parents('#deck_menu_container').length == 0) {
		$('#deck_menu_container').remove();
	}
};

study.scrollDeckMenu = function() {
	var ul = $('#deck_menu');
	var current_scroll_top_position = ul.scrollTop();
	var new_scroll_top_position = current_scroll_top_position;  // Just initialize it to some value
	if (study.scroll_deck_menu_direction == 'up') {
		new_scroll_top_position = current_scroll_top_position - 24;
	} else {
		new_scroll_top_position = current_scroll_top_position + 24;
	}
	var el = ul.get(0);
	el.scrollTop = new_scroll_top_position;
	new_scroll_top_position = ul.scrollTop();
	if (current_scroll_top_position == new_scroll_top_position) {
		clearInterval(study.scroll_deck_menu_interval);
		delete(study.scroll_deck_menu_interval);
	}
};

study.scrollDeckMenu_onePage = function(e) {
	study.scrollDeckMenu_stop(e); // clear the interval
	/*
	 * If the user clicks on the up / down arrow in the menu of decks,
	 * scroll up / down one page
	 */
	var ul = $('#deck_menu');
	var current_scroll_top_position = ul.scrollTop();
	var new_scroll_top_position = current_scroll_top_position;  // Just initialize it to some value
	if (study.scroll_deck_menu_direction == 'up') {
		new_scroll_top_position = current_scroll_top_position - (8 * 24);
	} else {
		new_scroll_top_position = current_scroll_top_position + (8 * 24);
	}
	var el = ul.get(0);
	el.scrollTop = new_scroll_top_position;
};

study.scrollDeckMenu_prep = function(e) {
	var $this = $(this);
	if ($this.attr('id') == 'deck_menu_arrow_up') {
		study.scroll_deck_menu_direction = 'up';
	} else {
		study.scroll_deck_menu_direction = 'down';
	}
	if (typeof(study.scroll_deck_menu_interval) != 'undefined') {
		clearInterval(study.scroll_deck_menu_interval);
		delete(study.scroll_deck_menu_interval);
	}
	study.scrollDeckMenu();
	study.scroll_deck_menu_interval = setInterval(study.scrollDeckMenu,500);
};

study.scrollDeckMenu_stop = function(e) {
	if (typeof(study.scroll_deck_menu_interval) != 'undefined') {
		clearInterval(study.scroll_deck_menu_interval);
		delete(study.scroll_deck_menu_interval);
	}
};

study.handleDeckMenuLinkClicked = function(e) {
	e.preventDefault();
	study.notify('Acknowledgement','<div style="text-align:center">Please wait</div>',{height:60, width:200});
	var $this = $(this);
	var value = $this.find('span').text();
	$('#hidden_setKey').text(value);
	$.astound_ajax_getJSON('/setlist.json',{'setKey': value},function(data) {
		study.displayEditEntriesAndStudyPage(data);
		study.closeNotification();
	});
	return false;
};

study.renderDeckListOnMouseOver = function() {
	var data = study.cached_deck_list;
	var list = data.list;
	var len = list.length;
	if ($('#deck_menu').length) {
		return;
	}
	var height = len * 24;
	var needScrolling = false;
	if (height > 10 * 24) {
		height = 10 * 24;
		needScrolling = true;
	}
	var menu = "<div id='deck_menu_container'><ul id='deck_menu'>";
	for (i = 0; i < len; i++) {
		var k = list[i][0];
		var title = list[i][1];
		var current = list[i][2];
		menu = menu + '<li><a class="deck_menu_link" href="#">' + title + '<span style="display:none">' + k + '</span></a></li>';
	}
	menu = menu + '</ul></div>';
	menu = $(menu);
	if (needScrolling) {
		menu.prepend('<div id="deck_menu_arrow_up_container"><div id="deck_menu_arrow_up"></div></div>');
		menu.append('<div id="deck_menu_arrow_down_container"><div id="deck_menu_arrow_down"></div></div>');
		var ul = menu.find('#deck_menu');
		ul.append('<li>&nbsp;</li>');
		ul.prepend('<li>&nbsp;</li>');
	}
	var pos = $('#current_deck_title').position();
	menu.css({'height': height + 'px', 'left': pos.left + 'px'});
	/*
	 * For this to work, we must also set the height of the ul element equal to the height of the container,
	 * and set overflow:hidden on the ul element
	 */
	menu.find('#deck_menu').css({'height': height + 'px', 'overflow': 'hidden'});
	menu.appendTo('#currentDeck');
	$('#deck_menu_arrow_up').mouseover(study.scrollDeckMenu_prep);
	$('#deck_menu_arrow_up').mouseout(study.scrollDeckMenu_stop);
	$('#deck_menu_arrow_up').click(study.scrollDeckMenu_onePage);
	$('#deck_menu_arrow_down').mouseover(study.scrollDeckMenu_prep);
	$('#deck_menu_arrow_down').mouseout(study.scrollDeckMenu_stop);
	$('#deck_menu_arrow_down').click(study.scrollDeckMenu_onePage);

	$('.deck_menu_link').click(study.handleDeckMenuLinkClicked);
	$('#deck_menu_container').mouseover();
	$('#deck_menu_container').mouseout(study.handle_removeDeckMenu);
};

study.displayEditEntriesAndStudyPage = function(json) {
	if (arguments.length == 1) {
		study.cached_deck_list = json;
	}
	var data = study.cached_deck_list;
	var list = data.list;
	var len = list.length;
	var html = "";
	var current_deck = "";
	for (i = 0; i < len; i++) {
		var k = list[i][0];
		var title = list[i][1];
		var current = list[i][2];
		var objective_calendarDays = list[i][3];
		if (current == 1) {
			if (! objective_calendarDays) {
				$('#objectiveMsg').removeClass('hideMe');
			}
			current_deck = 'You are editing: <span id="current_deck_title" style="text-decoration: underline">' + title + '</span><span id="entryCount_new"></span>';
			$('#hidden_setKey').text(k);
		}
	}

	$('#currentDeck').html(current_deck);
	$('#current_deck_title').mouseover(study.renderDeckListOnMouseOver);
	$('#currentDeck').removeClass('hideMe');
	$('#currentDeck_spacer').removeClass('hideMe');

	if (len) {
		study.isContributor = data.isContributor;
		if (! study.isContributor) {
			$('#menu_edit_deck').parent().hide();
		}
		if (study.isContributor) {
			$('#entries_search').parent().show();
		}
		study.tags = study.cached_deck_list.tags;
		study.renderTagList();
		var setKey = $('#hidden_setKey').text();
		$(".stripeMe tr").mouseover(function(){$(this).addClass("over");}).mouseout(function(){$(this).removeClass("over");});
		$(".stripeMe tr:nth-child(even)").addClass("alt");
		var count = $('#thelist').find('td.questionColumn').length;
		if (count == 0) {
			$('#thelistContainer').hide();
		}
		study.showAddOrEditEntryDiv();
		$('#entryCount_all').text(data.entryCount);
		study.entryCount = parseInt($('#entryCount_all').text());
		study.showOrHideTheListFooter();
		$('#entries_search_form').submit(study.entriesSearch_listView);
		$('#entries_search_table').removeClass('hideMe');
		$('#entries_search_btn').click(study.entriesSearch_listView);
		$('#study').click(study.startStudy);
		$('.NeedTooltip').speechbubble({url:'tooltips_speechbubble.txt'});
		$('#studyViewContainerDiv').removeClass('being_used_but_hidden');
		$('#listViewContainerDiv').removeClass('being_used_but_hidden');
		$('#entries_search_form').parent().removeClass('being_used_but_hidden');
		$('#thelist').find('tr').slice(1).remove();
		$('#thelistContainer').hide();
		$('#entries_search_result').html('');
		study.showDeckSpecificMenuEntries();
	} else if ((study.social) && (study.socialView != 'canvas')) {
	} else {
		study.removeEditors();
		study.hideDeckSpecificMenuEntries();
		$('#content').html('<p class="clear dialog">Your personal library is empty.  You can create your own deck using the "New Deck" link, or you can study existing decks contributed by other users by using the search box (just click the "Search" button).  Both of these items is located at the top of the screen.  Enjoy our service.  Lets us know if you have any problems, suggestions, etc.</p>');
		if ($('#footer').hasClass('hideMe')) {
			$('#footer').removeClass('hideMe');
		}
	}
};

study.renderSetList = function(data,loadCurrentSet) {
	study.cached_deck_list = data;
	var list = data.list;
	var len = list.length;
	var html = "";
	var current_deck = "";
	for (i = 0; i < len; i++) {
		var k = list[i][0];
		var title = list[i][1];
		var current = list[i][2];
		html = html + "<option class='setlist_option' value='" + k + "'";
		if (current == 1) {
			html = html + " selected='selected'";
			current_deck = 'You are editing: <span id="current_deck_title" style="text-decoration: underline">' + title + '</span>';
		}
		html = html + ">" + title + "</option>";
	}

	$('#currentDeck').html(current_deck);
	$('#current_deck_title').mouseover(study.renderDeckListOnMouseOver);
	$('#currentDeck').removeClass('hideMe');

	if (html != "") {
		html = '<form class="setlist" action="/" method="post"><select id="setlist_select">' + html + '</select></form>';
		$('div.setlist').html(html);
		$('#setlist_select').change(study.setlistChange);
		if (loadCurrentSet) {
			var value = study.getSelectedValue('#setlist_select');
			$('#hidden_setKey').text(value);
			study.removeEditors();
			study.renderTabs(data);
			$('.setlist_currentlySelected').unbind('mouseup').removeClass('.setlist_currentlySelected');
			var option = study.getSelectedOption('#setlist_select');
			option.mouseup(study.setlistUp).addClass('setlist_currentlySelected');
		}
	} else if ((study.social) && (study.socialView != 'canvas')) {
	} else {
		study.removeEditors();
		$('#content').html('<p class="clear dialog">Your personal library is empty.  You can create your own deck using the "New Deck" link, or you can study existing decks contributed by other users by using the search box (just click the "Search" button).  Both of these items is located on the top right corner of the screen.  Enjoy our service.  Lets us know if you have any problems, suggestions, etc.</p>');
		if ($('#footer').hasClass('hideMe')) {
			$('#footer').removeClass('hideMe');
			//$('.footer').not('#showHiddenElements').click(study.displayPage);
		}
	}
};

study.editEntry_cancel = function(json) {
	// we must not use the content of editors becaue they may have been modified
	study.removeEditors();
	$('.entry_edit').html(study.fetchTemplate('listViewRowTemplate_contributor'));
	$('.entry_edit').find('.questionColumn').html(json.q);
	$('.entry_edit').find('.answerColumn').html(json.a);
	$('.entry_edit').find('.contributorColumn').find('.entryKey').text(json.entryKey);
	var tagColumn = $('.entry_edit').find('.tagColumn');
	tagColumn.html('');
	for (var i = 0, j = json.tags.length; i < j; i++) {
		tagColumn.append('<span class="draggable">' + json.tags[i] + '</span><br/>');
	}
	$('.entry_edit').find('.draggable').astound_draggable();
	$('.entry_edit').find('.deletebtn').astound_droppable(study.deleteTag);
	$('.entry_edit').scrollIntoView();
	$('.entry_edit').removeClass('entry_edit');
	study.editEntry_showOtherControls();
};

study.addEntry_saveSelectedTagsFromDOM = function() {
	var tagNodes = $('#addOrEditEntryDiv').find('.tag_input');
	var tags = {};
	for (var i = 0, j = tagNodes.length; i < j; i++) {
		var node = $(tagNodes.get(i));
		var checked = node.attr('checked');
		if (checked) {
			var v = node.attr('value');
			tags[v] = true;
		}
	}
	study.addEntry_selectedTags_json = tags;
};

study.editEntry_showOtherControls = function() {
	study.showAddOrEditEntryDiv();
};

study.splitQueryArguments = function(str) {
	var result = {};
	str = str.replace(/.*?\?/,''); // remove everything before the ?
	str = str.replace(/#.*/,''); // remove the fragment, so what is left is just the query string
	var parts = str.split(/[&;]/);
	for (var i = 0, j = parts.length; i < j; i++) {
		var part = parts[i];
		var kv = part.split(/=/);
		result[kv[0]] = kv[1];
	}
	return result;
};

study.editEntry = function(e) {
	e.preventDefault();
	if (study.editing_an_entry === true) {
		return false;
	} else {
		study.editing_an_entry = true;
	}
	var cell;
	var question, answer, entryKey, setKey;
	if (e.type == 'dblclick') {
		study.edit_entry_mode = 'thelist';
		var cell = $(e.target);
		while (cell.parent().parent().parent().attr('id') != 'thelist') {
			cell = cell.parent();
		}
		var row = cell.parent();
		var cell = row.find('td.contributorColumn');
		var question = cell.prev().prev().prev().html();
		var answer = cell.prev().prev().html();
		var entryKey = cell.find('.entryKey').text();
		var setKey = study.getHiddenSetKey();
		var row = cell.parent();
		row.addClass('entry_edit');
		row.hide();
	} else if (e.type == 'click') {
		var el = $(e.target);
		if (el.attr('id') == 'edit_entry') {
			study.edit_entry_mode = 'study';
			var entryKey = $('#hidden_entryKey').text();
			var setKey = study.getHiddenSetKey();
		}
	}
	var data = {'entryKey': entryKey, 'setKey': setKey};
	$.astound_ajax({'url': '/entry/get.json', 'type': 'POST', 'dataType': 'json', 'data': data, 'success': function(json,textStatus){
			var question = json.q;
			var answer = json.a;
			study.showAddOrEditEntryDiv();
			study.renderTagTable(json.tags_json);
			$('#entryKey').val(entryKey);
			study.setEditorContent('question',question);
			study.setEditorContent('answer',answer);
			if (json.isPluginApplicable) {
				$('#entry_plugin_applicable_y').click();
			} else {
				$('#entry_plugin_applicable_n').click();
			}
			if (json.isQuizOrTestApplicable) {
				$('#entry_simple_y').click();
			} else {
				$('#entry_simple_n').click();
			}
			$('#addOrEditEntryDiv').scrollIntoView(true);
			if (study.edit_entry_mode == 'study') {
				$('.cancelbtn').click(function() { 
					study.setEditorContent('question','');
					study.setEditorContent('answer','');
					study.hideAddOrEditEntryDiv();
				});
			}
	}});
	return false;
}

study.getSelectedTagsFromDOM = function() {
	var tagNodes = $('#tagTableDiv').find('.tag_input');
	tags = [];
	for (var i = 0, j = tagNodes.length; i < j; i++) {
		var node = $(tagNodes.get(i));
		var checked = node.attr('checked');
		if (checked) {
			tags.push(node.attr('value'));
		}
	}
	return tags;
};

study.addEditors = function() {
	var c = $('textarea.loadEditor');
	for (var i = 0, j = c.length; i < j; i++) {
		var id = $(c.get(i)).attr('id');
		study.editors[id] = true;
	}
	tinyMCE.init(study.tinyMCESettings);
};

study.removeEditors = function() {
	var c = $('textarea.loadEditor');
	for (var i = 0, j = c.length; i < j; i++) {
		var id = $(c.get(i)).attr('id');
		var p = $(c.get(i)).parent();
		p.hide();
		var editor = tinyMCE.getInstanceById(id);
		if (editor) {
			editor.setContent('');
			$(id).hide();
			if (editor) editor.remove();
			$(id).show();
			p.show();
		}
	}
};

study.addClickHandlerForSets = function() {
	$("a.addset_setlist_link").click(study.renderSet);
};

study.renderSet = function(e) {
	e.preventDefault();
	var href = $(this).attr('href');
	var parameters = study.splitQueryArguments(href);
	var setKey = parameters['setKey'];
	$('#hidden_setKey').text(setKey);
	study.removeEditors();
	$.astound_ajax_getJSON('/setlist.json',{'setKey': setKey},function(data) {
		study.renderSetList(data,true);
	});
	// $.astound_ajax({'url': '/set/render.json', 'dataType': 'json', 'data': {'setKey': setKey}, 'success': study.renderTabs});
	return false;
};

study.getEditorContent = function(id) {
	var editor = tinyMCE.getInstanceById(id);
	return editor.getContent();
};

study.setEditorContent = function(id,content) {
	var editor = tinyMCE.getInstanceById(id);
	editor.setContent(content);
};

study.submitEditSetForm = function(e) {
	e.preventDefault();
	$('#editDeck_form').submit();
	/*
	var setKey = $("#editDeck_setKey").attr('value');
	var title = $("#editDeck_title").attr('value');
	var selectedIndex = $("#editDeck_visibility").attr('selectedIndex');
	var sel = $("#editDeck_visibility").get(0);
	var visibility = sel.options[selectedIndex].value;
	var materials = study.getEditorContent('editDeck_materials');
	var description = study.getEditorContent('editDeck_description');
	var data = {'title': title, 'visibility': visibility, 'setKey': setKey, 'materials': materials, 'description': description};
	var em = $('#email');
	if (em.length == 1) {
		var email = em.val();
		if ((typeof(email) != 'undefined') && (email != '')) {
			data.email = email;
		}
	}
	$.astound_ajax({'url': '/set/save.json', 'type': 'POST', 'dataType': 'json', 'data': data, 'async': false, 'success': function(json,txtStatus){ 
			window.location.reload();
	}});
	*/
	return false;
};

study.showAddOrEditEntryDiv = function() {
	if (study.isContributor) {
		$('#addOrEditEntryDiv').show();
		study.renderTagTable(study.addEntry_selectedTags_json);
		$('#addOrEditEntryDiv').scrollIntoView();
		$('#entry_plugin_applicable_y').click();
		$('#entry_simple_y').click();
	} else {
		$('#addOrEditEntryDiv').hide();
	}
}

study.showAddOrEditEntryDiv_handler = function(e) {
	e.preventDefault();
	study.showAddOrEditEntryDiv();
	return false;
};

study.addOrSaveEntry_success = function(json, textStatus) {
	var newRow = $('<tr class="thelist_entries"></tr>');
	newRow.html(study.fetchTemplate('listViewRowTemplate_contributor'));
	newRow.find('.entrySelection').find('input.entrySelectCheckbox').val(json.entryKey);
	newRow.find('.questionColumn').html(json.question);
	newRow.find('.answerColumn').html(json.answer);
	newRow.find('.contributorColumn').find('.entryKey').text(json.entryKey);
	var tagColumn = newRow.find('.tagColumn');
	tagColumn.html('');
	var tagsHtml = '';
	var tags = json.tags;
	for(var i = 0, j = tags.length; i < j; i++) {
		tagsHtml = tagsHtml + '<span class="draggable">' + tags[i] + '</span><br/>';
	}
	tagColumn.append(tagsHtml);
	tagColumn.find('.draggable').astound_draggable();
	newRow.astound_droppable(study.addTagToEntry);
	newRow.appendTo('#thelist');
	var rowCount = $('#thelist').find('td.questionColumn').length;
	if (rowCount > 0) {
		// show the table if it was previously hidden
		$('th.tagColumn').removeClass('being_used_but_hidden');
		$('th.contributorColumn').removeClass('being_used_but_hidden');
		$('#thelist').removeClass('being_used_but_hidden');
		$('#thelistContainer').show();
	}
	newRow.scrollIntoView();

	newRow.mouseover(function(){$(this).addClass("over");}).mouseout(function(){$(this).removeClass("over");});
	$(".stripeMe tr").removeClass('alt');
	$(".stripeMe tr:nth-child(even)").addClass("alt");
	$('.submitbtn').val('Add').enable();
	study.setEditorContent('question','');
	study.setEditorContent('answer','');
	study.entryCount = study.entryCount + 1;
	study.showOrHideTheListFooter();
	newRow.scrollIntoView();
};

study.renderEntry = function() {
	var currentEntry = study.set_json.currentEntry;
	var d = study.set_json.entries[currentEntry];
	d.view = 'study';
	d.shown = d.shown + 1;
	$('#study_status').text((currentEntry + 1) + ' / ' + study.set_json.entries.length); 
	$('#relatedEntries').html('');
	$.astound_ajax({'url': '/entry/get.json', 'type': 'POST', 'dataType': 'json', 'data': d, 'success': function(json,textStatus){
			d.q = json.q;
			d.a = json.a;
			d.tags = json.tags;
			d.tags_json = json.tags_json;
			$('#studyViewContainerDiv').find('.study_hideMe').addClass('hideMe');
			$('#studyViewContainerDiv').find('#study_question_div').html(json.q);
			$('#studyViewContainerDiv').find('#study_answer_div').html(json.a);
			$('#studyViewContainerDiv').find('#hidden_entryKey').text(d.entryKey);
			$('#studyViewContainerDiv').removeClass('hideMe');
		}
	});
};

study.adjustHeight = function(pixel) {
	if (study.social) {
		gadgets.window.adjustHeight(pixel);
	}
};

study.astound_adjustHeight = function(pixel) {
	if (study.social) {
		gadgets.window.adjustHeight(pixel);
		var d = new Date();
		window.location = '#';
	} else if (study.facebook) {
		window.location = '#';
	}
};

study.renderNextEntry = function(e) {
	e.preventDefault();
	study.set_json.currentEntry += 1;
	if (study.set_json.currentEntry == study.set_json.entries.length) study.set_json.currentEntry = 0;
	study.renderEntry();
	return false;
};

study.renderPreviousEntry = function(e) {
	e.preventDefault();
	study.set_json.currentEntry -= 1;
	if (study.set_json.currentEntry == -1) study.set_json.currentEntry = study.set_json.entries.length - 1;
	study.renderEntry();
	return false;
};

study.showAnswer = function(e) {
	e.preventDefault();
	$('#studyViewContainerDiv').find('.study_hideMe').removeClass('hideMe');
	var currentEntry = study.set_json.currentEntry;
	var d = study.set_json.entries[currentEntry];
	d.wrong = d.wrong + 1;
	var randomNumber = 10 + Math.floor(Math.random() * 10); // Generate a random number between 10 and 20
	if (currentEntry + randomNumber >= study.set_json.entries.length) {
		study.set_json.entries.push(d);
	} else {
		study.set_json.entries.splice(currentEntry + randomNumber, 0,d);
	}
	$.astound_ajax({'url': '/entry/processShowAnswer.json', 'type': 'POST', 'dataType': 'json', 'data': d});
	return false;
};

study.renderSetEntries = function(json, textStatus) {
	json.currentEntry = 0;
	study.set_json = json;
	$('#study').val('Study').enable();
	if (json.entries.length == 0) {
		study.notify('Information',"This deck (or tag) has no entries.");
		return;
	}
	$("#addOrEditEntryDiv").hide();
	$('#thelistContainer').hide();
	$('#studyViewContainerDiv').html(study.fetchTemplate('studyTableTemplate'));
	$('#show_answer').click(study.showAnswer);
	$('#next_entry').click(study.renderNextEntry);
	$('#previous_entry').click(study.renderPreviousEntry);
	if ((! study.social) || (study.socialView == 'canvas')) {
		if (json.contributor) {
			$('#edit_entry').removeClass('hideMe');
			$('#add_entry').removeClass('hideMe');
			$('#delete_entry').removeClass('hideMe').click(study.deleteEntry);
		}
		$('#entries_search_term').removeClass('hideMe');
		$('#entries_search_btn').removeClass('hideMe');
	}
	study.renderEntry();
};

study.deleteEntry = function(e) {
	e.preventDefault();
	var el = $(e.target);
	if (el.attr('id') == 'delete_entry') {
		// coming from the study section
		var entryKey = $('#hidden_entryKey').text();
		$.astound_ajax({'url': '/entry/delete.json', 'type': 'POST', 'dataType': 'json', data: {'entryKey': entryKey}});
		study.set_json.entries.splice(study.set_json.currentEntry,1);
		if (study.set_json.currentEntry == study.set_json.entries.length) {
			study.set_json.currentEntry = 0;
		}
		study.renderEntry();
	} else {
		var cell = el.parent();
		var entryKey = cell.find('.entryKey').text();
		$.astound_ajax({'url': '/entry/delete.json', 'type': 'POST', 'dataType': 'json', data: {'entryKey': entryKey}, 'success': function(){}});
		cell.parent().remove();
		if ($('#thelist').find('td.questionColumn').length == 0) {
			$('#thelistContainer').hide();
		}
		study.entryCount = study.entryCount - 1;
		study.showOrHideTheListFooter();
	}
	return false;
};

study.hideAddOrEditEntryDiv = function() {
	study.addEntry_saveSelectedTagsFromDOM();
	$('#addOrEditEntryDiv').hide();
}

study.addOrSaveEntry = function(e) {
	e.preventDefault();
	var question = $.trim(study.getEditorContent('question'));
	var answer = $.trim(study.getEditorContent('answer'));
	if ((! question) && (! answer)) {
		study.notify('Attention','Please enter content for at least one side.', {height: 60});
		return false;
	}
	var setKey = study.getHiddenSetKey();
	var entryKey = $('#entryKey').val();
	var tags = study.getSelectedTagsFromDOM();
	study.addEntry_saveSelectedTagsFromDOM();
	// save these for the purpose of updating the list view
	var data = {'question': question, 'answer': answer, 'setKey': setKey, 'tags': tags};
	data.entry_plugin_applicable = $("input:radio[name=entry_plugin_applicable]:checked").val();
	data.isQuizOrTestApplicable = $("input:radio[name=entry_simple]:checked").val();

	$(this).attr('value','Processing').disable();
	if ((entryKey != "") && (study.editing_an_entry === true)) {
		data.entryKey = entryKey;
		$.astound_ajax({'url': '/entry/update.json', 'type': 'POST', 'dataType': 'json', 'data': data});
		if (study.edit_entry_mode == 'thelist') {
			var editRow = $('.entry_edit');
			editRow.html(study.fetchTemplate('listViewRowTemplate_contributor'));
			editRow.find('.questionColumn').html(question);
			editRow.find('.answerColumn').html(answer);
			var tagColumn = editRow.find('.tagColumn');
			tagColumn.html('');
			var tagsHtml = '';
			for(var i = 0, j = tags.length; i < j; i++) {
				tagsHtml = tagsHtml + '<span class="draggable">' + tags[i] + '</span><br/>';
			}
			tagColumn.append(tagsHtml);
			tagColumn.find('.draggable').astound_draggable();
			editRow.find('.contributorColumn').find('.entryKey').text(entryKey);
			editRow.show();
			study.setEditorContent('question','');
			study.setEditorContent('answer','');
			$('#entryKey').val('');
			editRow.scrollIntoView();
			editRow.removeClass('entry_edit').mouseover();
		} else {
			$('#study_question_div').html(question);
			$('#study_answer_div').html(answer);
			study.setEditorContent('question','');
			study.setEditorContent('answer','');
			study.hideAddOrEditEntryDiv();
		}
		$('#entryKey').val('');
		study.editing_an_entry = false;
		$('#entry_plugin_applicable_y').click();
		$('#entry_simple_y').click();
	} else {
		$.astound_ajax({'url': '/entry/add.json', 'type': 'POST', 'dataType': 'json', 'async': false, 'data': data, 'success': study.addOrSaveEntry_success});
	}
	return false;
}

study.update_plugin_applicable_result = function() {
	study.notify('Information','Setting updated.');
}

study.showOrHideTheListFooter = function() {
	var displayText = '';
	if (study.entryCount == 1) {
		displayText = '1 entry';
	} else if (study.entryCount == 0) {
		displayText = '0 entries'
	} else {
		displayText = study.entryCount + ' entries';
	}
	displayText = ' (' + displayText + ')';
	$('#entryCount_new').html(displayText);

	var found = $('#thelist').find('td.questionColumn').length;
	if (found == 0) {
		$('.thelist_footer').hide();
	} else {
		$('.thelist_footer').show();
	}
};

study.shareOnFacebook_click = function(e) {
	e.preventDefault();
	var u = study.cached_deck_list.shortUrl;
	t = study.cached_deck_list.title;
	window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), 'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
};

study.tinyMCE_init_instance_callback = function(inst) {
	// study.log('tinyMCE_init_instance_callback called');
};

study.tinyMCESettings = {
	mode: "textareas",
	theme: "advanced",
	format: "html",
	cleanup: true,
	tab_focus: ":prev,:next",
	plugins: "safari,style,table,advimage,advlink,inlinepopups,media,searchreplace,directionality,fullscreen",
	theme_advanced_buttons1 : "fullscreen,search,replace,undo,redo,ltr,rtl,code,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,link,unlink,image,sub,sup,formatselect,media,charmap",
	theme_advanced_buttons2 : "",
	theme_advanced_buttons3 : "",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_resizing : true,
	theme_advanced_path: false,
	theme_advanced_resize_horizontal: false,
	template_external_list_url : "/tinymce/examples/lists/template_list.js",
	external_link_list_url : "/tinymce/examples/lists/link_list.js",
	external_image_list_url : "/tinymce/examples/lists/image_list.js",
	media_external_list_url : "/tinymce/examples/lists/media_list.js",
	init_instance_callback: 'study.tinyMCE_init_instance_callback',
	setup: function(ed) { 
		ed.onClick.add(function(ed) {
			if (study.floating_tag_table_visible) {
				$('#floatingTagsDivOuter').dialog('close'); 
			}
		}); 
	}
};

study.add_fbuid_for_facebook_user = function() {
	var x = 5;
};

study.facebook_logout = function(e) {
	e.preventDefault();
	FB.Connect.logout(function(){
		$.cookie("sessionid", null);
		window.location.href = '/';
	});
	//FB.Connect.logoutAndRedirect(window.location.href);
	return false;
};

study.google_friend_connect_logout = function(e) {
	e.preventDefault();
	$.cookie("sessionid", null);
	google.friendconnect.requestSignOut();
	return false;
};

$.ajaxSetup({'async': false});
//$.ajaxSetup({'async': false, 'beforeSend': study.removeEditors});
$.ajaxSetup({'async': false, 'beforeSend': study.add_fbuid_for_facebook_user});
